import givenchy.Role
import givenchy.User
import givenchy.Task 
import givenchy.TaskGroup 
import grails.util.Environment


class BootStrap {

   
    def authenticateService
    def cacheService
    def init = { servletContext ->



            ['ROLE_USER':'普通用户',
                'ROLE_ADMIN':'系统管理员'].each{ entry ->
                 new Role(authority:entry.key,
                                description:entry.value).save()
                }

                if (!User.findByUsername('admin')) {
                    def person = new User(username: 'admin' ,email:'halleluja@126.com', enabled : true,lastTime:new Date())
                    person.passwd = authenticateService.encodePassword('1qazxsw2')
                    person.save()
                    Role.findByAuthority("ROLE_ADMIN").addToPeople(person) 
                }


            switch (Environment.current) {
            case Environment.DEVELOPMENT:
                System.out = new  PrintStream(System.out, true, "gbk") 

                initData()

            break
            case Environment.PRODUCTION:
                System.out = new  PrintStream(System.out, true, "utf-8") 
            break
            }

                cacheService.initTask()

    }

    def initData = {
        20.times{
            def person = new User(username: 'task' + it ,email: "task${it}@126.com", 
                enabled : true,lastTime:new Date() , 
                total : 300)
            person.passwd = authenticateService.encodePassword('123123')
            if (person.save()) {
                  Role.findByAuthority("ROLE_USER").addToPeople(person) 

                def taskGroup = new TaskGroup(name: "TaskGroup" + it ,
                    hourRate : "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0",
                    description: "description",
                    person : person)
                if (taskGroup.save() ) {
                           def task = new Task(name: "task"  + it, actions : "open, http://www.baidu.com" , person : person , taskGroup : taskGroup)
                    task.save()

                    taskGroup.addToTasks(task)
                    taskGroup.save()
                }else{
                    taskGroup.errors.each{
                        println "boot : " + it
                    }
                }

         
            } 
        }
    }


    def destroy = {

        cacheService.sync()
        cacheService.syncTask()
    }
}
